package com.xlf.service.base.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ZipUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xlf.common.core.exception.BizException;
import com.xlf.common.core.util.ServletUtils;
import com.xlf.common.core.util.StringUtils;
import com.xlf.common.core.util.file.UploadConfig;
import com.xlf.pojo.base.Problem;
import com.xlf.pojo.base.ProblemCase;
import com.xlf.pojo.constant.Constants;
import com.xlf.service.base.mapper.ProblemMapper;
import com.xlf.service.base.service.ProblemCaseService;
import com.xlf.service.base.mapper.ProblemCaseMapper;
import com.xlf.service.base.service.importProblem.AbstractImportService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.BindException;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;

import static com.xlf.pojo.constant.Constants.File.TESTCASE_BASE_FOLDER;

/**
* @author 小新
* @description 针对表【problem_case】的数据库操作Service实现
* @createDate 2023-11-27 16:55:07
*/
@Service
public class ProblemCaseServiceImpl extends ServiceImpl<ProblemCaseMapper, ProblemCase>
    implements ProblemCaseService{

    @Resource
    ProblemMapper problemMapper;

    @Override
    public void downloadTestcase(Long pid,Long id) throws IOException {

        Problem problem = problemMapper.selectById(pid);

        if(problem == null)
            throw new BindException("题目不存在");

        ProblemCase problemCase = getById(id);
        if(problemCase == null)
            throw new BindException("测试用例不存在");

        //从文件读
        if(problem.getTestCaseSource() == 1){
            String base = UploadConfig.getLocalPath() + TESTCASE_BASE_FOLDER.getPath() + '/' + pid;
            String input = problemCase.getInput();
            String output = problemCase.getOutput();
            if(StringUtils.isNotEmpty(input)){
                problemCase.setInput(FileUtil.readUtf8String(new File(base + '/' + input)));
            }
            if(StringUtils.isNotEmpty(output)){
                problemCase.setOutput(FileUtil.readUtf8String(new File(base + '/' + output)));
            }
        }

        String basePath = AbstractImportService.initFileDir();

        String seq = Optional.ofNullable(problemCase.getSeq()).orElse(1).toString();
        FileUtil.writeUtf8String(problemCase.getInput(),basePath + "/" + seq + ".in");
        FileUtil.writeUtf8String(problemCase.getOutput(),basePath + "/" + seq + ".out");
        File zip = ZipUtil.zip(basePath);
        HttpServletResponse response = ServletUtils.getResponse();
        response.setContentType("application/octet-stream; charset=UTF-8");
        response.getOutputStream().write(FileUtil.readBytes(zip));

    }


}




